<?php

namespace app\common\model\wash;

use app\common\model\Admin;
use think\Model;
use traits\model\SoftDelete;


use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use app\common\model\Coreorder;
use app\common\model\coupon\Log as Couponlog;
use app\common\model\ScoreLog;
use app\common\model\shop\Data;
use app\common\model\User;
use app\common\model\user\Address;
use app\common\model\UserGroup;
use think\Exception as ThinkException;
use think\Hook;

class Order extends Model
{

    use SoftDelete;



    // 表名
    protected $name = 'wash_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'paytime_text',
        'status_text',
        'shop_status_text',
        'factory_status_text',
        'send_type_text',
        'pay_type_text',
        'canceltime_text',
        'taketime_text',
        'warehousingtime_text',
        'createtime_text',
        'factory_f_image_str',
        'factory_b_image_str',
        'is_urgent_text',
        'factory_images_array',
    ];
    public function getFactoryFImageStrAttr($value, $data)
    {
        return isset($data['factory_f_image']) && $data['factory_f_image'] ? cdnurl($data['factory_f_image'], true) : '';
    }
    public function getFactoryBImageStrAttr($value, $data)
    {
        return isset($data['factory_b_image']) && $data['factory_b_image'] ? cdnurl($data['factory_b_image'], true) : '';
    }

    public function getFactoryImagesArrayAttr($value, $data)
    {
        if (isset($data['factory_images']) && $data['factory_images']) {
            $arr = explode(',', $data['factory_images']);
            foreach ($arr as &$v) {
                $v = cdnurl($v, true);
            }
            return $arr;
        }
        return [];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3'), '4' => __('Status 4'), '-1' => __('Status -1')];
    }

    public function getShopStatusList()
    {
        return ['0' => __('Shop_status 0'), '1' => __('Shop_status 1'), '2' => __('Shop_status 2'), '3' => __('Shop_status 3'), '4' => __('Shop_status 4')];
    }

    public function getFactoryStatusList()
    {
        return ['0' => __('Factory_status 0'), '1' => __('Factory_status 1'), '2' => __('Factory_status 2')];
    }

    public function getSendTypeList()
    {
        return ['1' => __('Send_type 1'), '2' => __('Send_type 2')];
    }

    public function getPayTypeList()
    {
        return ['wxpay' => __('Pay_type wxpay'), 'money' => __('Pay_type money')];
    }

    public function getIsUrgentList()
    {
        return ['0' => __('Is_urgent 0'), '1' => __('Is_urgent 1')];
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getShopStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['shop_status']) ? $data['shop_status'] : '');
        $list = $this->getShopStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getFactoryStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['factory_status']) ? $data['factory_status'] : '');
        $list = $this->getFactoryStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getSendTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['send_type']) ? $data['send_type'] : '');
        $list = $this->getSendTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getWarehousingtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['warehousingtime']) ? $data['warehousingtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getCanceltimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['canceltime']) ? $data['canceltime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getTaketimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['taketime']) ? $data['taketime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getIsUrgentTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_urgent']) ? $data['is_urgent'] : '');
        $list = $this->getIsUrgentList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCanceltimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setTaketimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function goods()
    {
        return $this->belongsTo('Goods', 'goods_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function shop()
    {
        return $this->belongsTo('app\common\model\User', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function factory()
    {
        return $this->belongsTo('app\common\model\User', 'factory_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function company()
    {
        return $this->belongsTo('app\common\model\Admin', 'company_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function regional()
    {
        return $this->belongsTo('app\common\model\Admin', 'regional_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    /**
     * 创建订单
     */
    static function createOrder($user, $shop_id, $address_id, $pay_type, $send_type = '1', $is_urgent = 0, $apply_time = null, $coupon_id, $use_credit, $goods_id, $num = 1, $cart_ids, $remark = '')
    {
        $group = UserGroup::get($user->group_id);
        $address = Address::get($address_id);
        // if (!$address) {
        //     return ['code' => 1, 'msg' => '地址未找到'];
        // }
        $shop = User::where('id', $shop_id)->find();
        if (!$shop) {
            return ['code' => 1, 'msg' => '店铺未找到'];
        }

        // $factory = User::where('id', $shop->factory_id)->find();
        // if (!$factory) {
        //     return ['code' => 1, 'msg' => '工厂未找到'];
        // }

        $total_fee = 0;
        $send_fee = 0;
        $urgent_price = 0;
        $urgent_fee = 0; //urgent_fee
        $discount_fee = 0;

        // if ($send_type == '1') {
        //     $send_fee = config('site.send_price') ?? 4;
        // }
        // $urgent_price = config('site.urgent_price') ?? 10;

        $order_info = [];
        if ($goods_id) {
            //单商品购买
            if ($num < 1) {
                return ['code' => 1, 'msg' => '数量最低为1'];
            }
            $goods = Goods::get($goods_id);
            if (!$goods) {
                return ['code' => 1, 'msg' => '商品未找到'];
            }

            $factory = Data::with('factory')->where('data.shop_id', $shop_id)->where('data.category_id', $goods->category_id)->find();
            if (!$factory) {
                return ['code' => 1, 'msg' => '工厂未找到'];
            }
            $company = Admin::where('id', $factory->factory->company_id)->find();
            if (!$company) {
                return ['code' => 1, 'msg' => '公司未找到'];
            }

            $regional = Admin::region($company->region_id);
            if (!$regional) {
                return ['code' => 1, 'msg' => '区域公司未找到'];
            }


            if ($send_type == '1') {
                $send_fee = $regional->send_price ?? 4;
            }
            $urgent_price = $regional->urgent_price ?? 10;

            for ($i = 0; $i < $num; $i++) {
                $discount_fee = bcmul($goods->goods_price, 1 - $group->discount / 100, 2);
                $total_price = bcsub($goods->goods_price, $discount_fee, 2);
                $total_fee = bcadd($total_fee, $total_price, 2);
                if ($is_urgent) {
                    $urgent_fee += $urgent_price;
                }

                $order_no = Coreorder::getorderno();
                array_push($order_info, [
                    'user_id' => $user->id,
                    'discount_fee' => $discount_fee,
                    'company_id' => $company->id,
                    'factory_id' => $factory->factory_id,
                    'regional_id' => $regional->id,
                    'pay_type' => $pay_type,
                    'send_type' => $send_type,
                    'is_urgent' => $is_urgent,
                    'remark' => $remark,
                    'shop_id' => $shop_id,
                    'sn' => $order_no,
                    'goods_fee' => $goods->goods_price,
                    'total_fee' => $total_price,
                    'send_fee' => $send_fee,
                    'urgent_fee' => $is_urgent ? $urgent_price : 0,
                    'goods_name' => $goods->goods_name,
                    'goods_id' => $goods->id,
                    'apply_time' => $apply_time,
                    'address_id' => $address_id,
                    'address' => ($address->province ?? '') . ($address->city ?? '') . ($address->district ?? '') . ($address->address ?? ''),
                    'consignee' => $address->contact ?? '',
                    'phone' => $address->telephone ?? '',
                    'coupon_id' => $coupon_id
                    // 'price' => $goods->goods_price,
                ]);
            }
        } elseif ($cart_ids) {
            //购物车购买
            if (!is_array($cart_ids)) {
                $cart_ids = explode(',', $cart_ids);
            }
            if (count($cart_ids) <= 0) {
                return ['code' => 1005, 'msg' => '商品为空'];
            }

            $carts = Cart::all($cart_ids);

            foreach ($carts as $k => $c) {
                // $fa_id = Data::where('shop_id', $shop_id)->where('category_id', $c->goods->category_id)->value('factory_id') ?? $factory->id;
                $factory = Data::with('factory')->where('data.shop_id', $shop_id)->where('data.category_id', $c->goods->category_id)->find();
                if (!$factory) {
                    return ['code' => 1, 'msg' => '门店未找到' . $c->goods->id];
                }
                $company = Admin::where('id', $factory->factory->company_id)->find();
                if (!$company) {
                    return ['code' => 1, 'msg' => '区县公司未找到'];
                }
                $regional = Admin::region($company->region_id);
                if (!$regional) {
                    return ['code' => 1, 'msg' => '城市公司未找到'];
                }
                if ($send_type == '1') {
                    $send_fee += $regional->send_price ?? 4;
                }
                $urgent_price = $regional->urgent_price ?? 10;

                for ($i = 0; $i < $c->num; $i++) {

                    if (!$c->goods || $c->goods->status == '0') {
                        return ['code' => 1005, 'msg' => '商品未找到或已下架'];
                    }

                    $discount_fee = bcmul($c->goods->goods_price, 1 - $group->discount / 100, 2);
                    $total_price = bcsub($c->goods->goods_price, $discount_fee, 2);
                    $total_fee = bcadd($total_fee, $total_price, 2);
                    if ($is_urgent) {
                        $urgent_fee += $urgent_price;
                    }
                    $order_no = Coreorder::getorderno();

                    array_push($order_info, [
                        'user_id' => $user->id,
                        'company_id' => $company->id,
                        'factory_id' => $factory->factory_id,
                        'regional_id' => $regional->id,
                        'discount_fee' => $discount_fee,
                        'pay_type' => $pay_type,
                        'send_type' => $send_type,
                        'is_urgent' => $is_urgent,
                        'remark' => $remark,
                        'shop_id' => $shop_id,
                        'sn' => $order_no,
                        'goods_fee' => $c->goods->goods_price,
                        'total_fee' => $total_price,
                        'send_fee' => $send_fee,
                        'urgent_fee' => $is_urgent ? $urgent_price : 0,
                        'goods_name' => $c->goods->goods_name,
                        'goods_id' => $c->goods->id,
                        'apply_time' => $apply_time,
                        'address_id' => $address_id,
                        'address' => ($address->province ?? '') . ($address->city ?? '') . ($address->district ?? '') . ($address->address ?? ''),
                        'consignee' => $address->contact ?? '',
                        'phone' => $address->telephone ?? '',
                        'coupon_id' => $coupon_id
                        // 'price' => $goods->goods_price,
                    ]);
                }
            }

            // return ['code' => 0, 'data' => $order];
        }


        //使用优惠券
        if ($coupon_id) {
            $coupon_log = Couponlog::where('id', $coupon_id)->where('city_id', $regional->id)->where('user_id', $user->id)->where('state', '1')->find();
            if (!$coupon_log) {
                return ['code' => 1, 'msg' => '无效的优惠券'];
            }
            if ($coupon_log < date('Y-m-d')) {
                return ['code' => 1, 'msg' => '优惠券已过期'];
            }

            if ($coupon_log->money > ($total_fee + $send_fee + $urgent_fee)) {
                return ['code' => 1, 'msg' => '优惠券不满足使用条件'];
            }
        }

        Db::startTrans();
        try {
            //使用优惠券
            if ($coupon_id) {
                $coupon_log->state = '2';
                $coupon_log->save();
            }

            $coupon_fee = $coupon_id ? $coupon_log->price : 0;

            $total_pay_fee = $total_fee + $send_fee + $urgent_fee - $coupon_fee;

            //积分抵扣
            $credit_fee = 0;
            $use_credit = intval($use_credit);
            if ($use_credit) {
                $credit_fee = $use_credit / (config('site.integral_ratio') ?? 10);
                if ($credit_fee > $total_pay_fee) {
                    $credit_fee = $total_pay_fee;
                    $use_credit = $credit_fee * (config('site.integral_ratio') ?? 10);
                }
            }

            $total_pay_fee = $total_pay_fee - $credit_fee;

//            $send_credit_fee = $use_credit ? ($credit_rate > 0 ? (bcmul($send_fee, $credit_rate, 2)) : $send_fee) : 0;

            $core_data = [
                'order_id' => 0,
                'user_id' => $user->id,
                'module_mark' => 'wash',
                'fee' => $total_pay_fee,
                'order_no' => Coreorder::getorderno(),
                'coupon_id' => $coupon_id,
                'coupon_fee' => $coupon_fee,
                'is_usecoupon' => $coupon_id ? 1 : 0,
//                'send_credit_fee' => $send_fee,
                'send_use_credit' => $send_fee * (config('site.integral_ratio') ?? 10),
                'send_fee' => $send_fee,
            ];

            Cart::where('id', 'in', $cart_ids)->delete();

            if ($pay_type == 'wxpay') {
                //创建核心订单
                $core_order = new Coreorder($core_data);
                $core_order->save();
            } elseif ($pay_type == 'money') {
                //余额支付
                if ($user->commission < $total_pay_fee) {
                    Db::rollback();
                    return ['code' => 2006, 'msg' => '余额不足'];
                }
                $core_data['fee'] = 0;
                $core_data['send_money_fee'] = $core_data['send_fee'];
                $core_data['send_fee'] = 0;

                $core_order = new Coreorder($core_data);
                $core_order->save();


                User::cmoney(-$total_pay_fee, $user->id, '支付服务订单ID' . $core_order->id);


                // return ['code' => 0, 'data' => ['need_pay' => 0, 'order_id' => $order->id]];
            }

            if ($use_credit && $use_credit > 0) {
                // User::score(-$use_credit, $user->id, '支付服务订单ID' . $core_order->id);
                ScoreLog::income($user->id, $use_credit, 1, 400, $core_order->order_no);
                //ScoreLog::create(['user_id' => $user->id, 'score' => -$data['use_credit'], 'before' => $user->score, 'after' => $user->score - $data['use_credit'], 'memo' => '支付服务订单ID' . $order->id]);
            }

            $order_count = count($order_info);

            $rate = 1;
            foreach ($order_info as $k => &$v) {
                // $v['use_credit'] = $use_credit? bcmul(bcmul(($v['urgent_fee']+$v['goods_fee']),$coupon_rate,2),$credit_rate,2):0;金额
                $v['coreorder_id'] = $core_order->id;
                // $v['send_fee'] = $coupon_rate > 0 ? bcmul($v['send_fee'], $coupon_rate, 2) : 0;
                if ($v['send_fee'] > 0 && $order_count > 0) {
                    $v['send_fee'] = bcdiv($v['send_fee'], $order_count, 2);
                }

                if ($k + 1 == $order_count) {
                    $k_rate = $rate;
                } else {
                    $k_rate = bcdiv($v['total_fee'] , $total_fee, 5);
                    $rate = bcsub($rate, $k_rate, 5);
                }

                // 优惠券抵扣金额均摊
                if ($coupon_id) {
                    $v['coupon_fee'] = bcmul($coupon_fee, $k_rate, 2);
                    $v['total_fee'] = $v['total_fee'] - $v['coupon_fee'];
                }

                // 加急费金额均摊
                $v['urgent_fee'] = bcmul($urgent_fee, $k_rate, 2);

                // 积分抵扣金额均摊
                $v['credit_fee'] = bcmul($credit_fee, $k_rate, 2);
                $v['use_credit'] = $v['credit_fee'] * (config('site.integral_ratio') ?? 10);

                $v['total_fee'] = $v['total_fee'] + $v['urgent_fee'];
                if ($pay_type == 'wxpay') {
                    $v['pay_fee'] = $v['total_fee'];
                } else {
                    $v['money_fee'] = $v['total_fee'];
                }

                // $v['discount_fee'] =  $discount_fee;
            }

            $order = new self();
            $order->saveAll($order_info);

            # - 第一次下单 用户就归属指定驿站/门店和所属区市
            if ($user->shop_id <= 0) {
                $user->shop_id = $shop_id;
                $user->factory_id = $factory->factory_id;
                $user->company_id = $company->id;
                $user->city_id = $regional->region_id;
                $user->region_id = $company->region_id;
                $user->city = $regional->region;
                $user->region = $company->region;

                $user->save();
            }
            Db::commit();
            if ($pay_type == 'money') {
                self::payok($core_order->id);
            }
            return ['code' => 0, 'data' => ['need_pay' => $core_order->fee > 0 ? 1 : 0, 'core_id' => $core_order->id]];
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 3, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取价格
     */
    static function getOrderPriceInfo($user, $goods_id, $num = 1, $cart_ids, $send_type = '1', $is_urgent = 0, $coupon_id = 0, $shop_id = 0)
    {
        $group = UserGroup::get($user->group_id);
        $send_fee = 0;
        $urgent_fee = 0;

        $goods_info = [];

        $data = [
            'total' => 0,
            'total_fee' => 0,
            'discount_price' => 0,
        ];

        $shop = User::where('id', $shop_id)->find();
        if (!$shop) {
            return ['code' => 1, 'msg' => '门店未找到'];
        }
        $company = Admin::where('id', $shop->company_id)->find();
        if (!$company) {
            return ['code' => 1, 'msg' => '区县公司未找到'];
        }
        $regional = Admin::region($company->region_id);
        if (!$regional) {
            return ['code' => 1, 'msg' => '城市公司未找到'];
        }
        if ($send_type == '1') {
            $send_fee = $regional->send_price ?? 4;
        }
        $urgent_price = $regional->urgent_price ?? 10;

        if ($goods_id) {
            //单商品购买
            $goods = Goods::get($goods_id);

            if ($is_urgent) {
                $urgent_fee += $urgent_price * $num;
            }

            $data['total'] = $num;
            $goods_price = bcmul($goods->goods_price, $group->discount / 100, 2);
            $data['total_fee'] = abs(floatval($num * $goods_price));
            $data['discount_price'] = bcsub($data['total_fee'], $num * $goods->goods_price, 2);
            array_push($goods_info, [
                'id' => $goods->id,
                'goods_name' => $goods->goods_name,
                'image' => $goods->image,
                'total' => $num,
                'price' => $goods->goods_price
            ]);
            if ($is_urgent) {
                $urgent_fee += $urgent_price * $num;
            }
        } elseif ($cart_ids) {
            //购物车购买
            if (!is_array($cart_ids)) {
                $cart_ids = explode(',', $cart_ids);
            }

            $carts = Cart::all($cart_ids);

            //检查库存
            foreach ($carts as $k => $c) {

                $data['total'] += $c->num;
                $goods_price = bcmul($c->goods->goods_price, $group->discount / 100, 2);
                $data['total_fee'] += $c->num * $goods_price;

                $data['discount_price'] += bcsub($c->num * $goods_price, $c->num * $c->goods->goods_price, 2);

                array_push($goods_info, [
                    'id' => $c->goods->id,
                    'goods_name' => $c->goods->goods_name,
                    'image' => $c->goods->image,
                    'total' => $c->num,
                    'price' => $c->goods->goods_price
                ]);
                if ($is_urgent) {
                    $urgent_fee += $urgent_price * $c->num;
                }
            }
        }
        $data['total_fee'] = sprintf("%.2f", $data['total_fee']);
        $data['urgent_fee'] = sprintf("%.2f", $urgent_fee);
        $data['send_fee'] = sprintf("%.2f", $send_fee);


        $data['goods_info'] = $goods_info;
        if ($coupon_id) {
            $coupon = Couponlog::where('id', $coupon_id)
                ->where('user_id', $user->id)
                ->where('state', '1')
                ->where('city_id', $regional->id)
                ->where('enddate', '>=', date('Y-m-d'))->find();
        } else {
            $coupon = Couponlog::where('user_id', $user->id)
                ->where('state', '1')
                ->where('enddate', '>=', date('Y-m-d'))
                ->where('city_id', $regional->id)
                ->where('money', '<=', $data['total_fee'] + $data['urgent_fee'] + $data['send_fee'])
                ->order('price desc')
                ->find();
        }

        $data['coupon_info'] = $coupon;

        return $data;
    }


    static function cancel($order)
    {
        if ($order->status != '1') {
            return ['code' => 1006, 'msg' => '状态错误'];
        }
        $core_order = Coreorder::get($order->coreorder_id);
        if ($order->pay_fee > 0) {
            $res = Coreorder::refund($core_order, $order->pay_fee, 'R_' . $order->sn);
            if ($res['code'] != 0) {
                return $res;
            }
        }

        if ($order->use_credit > 0) {
            // User::score($order->use_credit, $order->user_id, '取消订单退回');
            ScoreLog::income($order->user_id, $order->use_credit, 2, 401, $core_order->order_no);
        }

        if ($order->money_fee > 0) {
            User::cmoney($order->money_fee, $order->user_id, '取消订单退回');
        }

        $order->status = '-1';
        $order->save();

        //退运费
        $has = self::where('coreorder_id', $order->coreorder_id)->where('status', '<>', '-1')->count();
        if (!$has) {
            // $core_order = Coreorder::get($order->coreorder_id);
            if ($core_order) {
                if ($core_order->send_fee) {
                    $res = Coreorder::refund($core_order, $order->send_fee, 'R_' . $core_order->order_no);
                }

                if ($core_order->send_credit_fee) {
                    ScoreLog::income($order->user_id, $core_order->send_credit_fee, 2, 401, $core_order->order_no);

                    // User::score($core_order->send_credit_fee, $order->user_id, '取消订单退回运费');
                }

                if ($core_order->send_money_fee) {
                    User::cmoney($core_order->send_money_fee, $order->user_id, '取消订单退回运费');
                }
            }
        }
        return ['code' => 0, 'msg' => '成功'];
    }


    /**
     * 重新支付
     * @Author xy
     * @Date 2023-07-21 09:55:20
     * @LastEditors xy
     * @LastEditTime Do not edit
     * @Description 
     * @param {*} $user
     * @param {*} $core_order_id
     * @param {*} $pay_type
     */
    public static function repay($user, $id, $pay_type)
    {
        $core_order = Coreorder::get($id);

        $orders = self::where('coreorder_id', $id)->select();
        if ($core_order && $orders) {
            if ($pay_type == 'money') {
                // 微信改余额
                Db::startTrans();
                try {
                    // 判断余额
                    if ($user->commission < $core_order->fee) {
                        Db::rollback();
                        return ['code' => 2006, 'msg' => '余额不足'];
                    }
                    $core_order->send_money_fee = $core_order->send_fee;
                    $core_order->send_fee = 0;
                    $core_order->fee = 0;
                    $core_order->save();
                    foreach ($orders as $order) {
                        $order->money_fee = $order->pay_fee;
                        $order->pay_fee = 0;
                        $order->save();
                    }

                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    return ['code' => 1, 'msg' => '操作异常' . $e->getMessage() . $e->getLine()];
                }
                self::payok($id);
                return ['code' => 0];
            }
        }

        return ['code' => 2, 'msg' => '不能这样操作'];
    }
    /**
     * 支付成功
     */
    static function payok($id)
    {
        $orders = self::where('coreorder_id', $id)->select();
        foreach ($orders as $order) {
            if ($order && $order->status == '0') {
                $order->status = '1';
                $order->paytime = time();
                //生成核销码
                $path = 'uploads/qrcode';
                $save_path = mkqrcode($order->sn, $path, md5($order->sn));

                $order->qrcode_image = APP_URL . '/' . $save_path;
                $order->save();


                $params = [
                    'mobile'   => $order->shop->mobile ?? '',
                    // 'msg'      => 1234,
                    'msg'      => $order->sn ?? '',

                    'template' => 'notice_shop',
                ];
                $result = Hook::listen('sms_notice', $params, null, true);

                $params = [
                    'mobile'   => $order->factory->mobile ?? '',
                    // 'msg'      => 1234,
                    // 'msg'      => $order->user->nickname ?? '用户',
                    'msg'      => $order->sn ?? '',


                    'template' => 'notice_factory',
                ];
                $result = Hook::listen('sms_notice', $params, null, true);
                Goods::where('id', $order->goods_id)->inc('sales', 1)->update();
                // // 佣金结算
                // if ($order->pay_fee > 0 || $order->money_fee) {
                //     Commission::addCommission($order);
                //     Commission::addFxCommission($order);
                // }
            }
        }
    }
}
